<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\CustomerSessionInfo;
use App\Service\WechatService;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public $request, $shopService, $indexService;


    /**
     * 新版登录接口，只通过code获取用户信息，不进行ENCRYPTED DATA解密
     * @param Request $request
     * @return array
     */
    public function login(Request $request)
    {
        try {
            $wechat = app('wechat');
            $code = $request->header('X-WX-Code');

            if (empty($code)) {
                throw new \Exception('请求头中未包含：X-WX-Code');
            }
            app('log')->debug('code: ' . var_export($code, true));

            $sessionInfo = $wechat->auth->session($code);
            app('log')->debug('session: ' . var_export($sessionInfo, true));
            // 4. 储存到数据库中

            $userResult = CustomerSessionInfo::storeUserInfo2($sessionInfo);
            $res = $userResult['model'];


            // 组装诚小程序的格式
            $data = [
                'skey' => $res->skey,
                'userinfo' => [
                    'id' => $res->id,
                    'openId' => $res->open_id,
                    'unionId' => $res->union_id,
                    'nickName' => $res->nick_name,
                    'avatarUrl' => $res->avatar_url,
                    'city' => $res->city,
                    'gender' => $res->gender,
                    'phone' => $res->phone,
                    'platform' => $res->platform,
                    'is_new_user' => $userResult['is_new_user'],
                ],
            ];
            app('log')->debug('userInfo: ' . var_export($data, true));

            return makeResponse($data, 'success', 200);
        } catch (\Exception $exception) {
            app('log')->error('微信登录失败：' . $exception->getTraceAsString());

            return makeResponse([], $exception->getMessage() . ' [LINE]:' . $exception->getLine(), 500);
        }
    }



    public function decryptData(Request $request)
    {
        $encryptedData = $request->input('encrypted_data',
            'hTdbUsgdhtW7fnLR4Q0jVNvrYigmPiHO4psneiYs+LWDArTJ8syFmLGul1DZ0r/mPLktPiYYukD49+hUeEWXsk1G4DA3xfCzGZ+qAcOzRcjqk0DI4ctQcGC3yw+us9KIAT2HG4dwOfr8KCJjhIBmYxvgcBttc87EcrTYVO/oUwpGxyZOrqs5rlYZ1MpqRyRTlOQKG67QZS5gMO3bH7N0nA==');
        $iv = $request->input('iv', '/TKaZcnTGA6E+2LjLJs6Xw==');
        $user = $request->user();
        if (!$user) {
            return makeResponse([], '请使用微信登陆', 500);
        }
        if (empty($encryptedData)) {
            throw new \Exception('请求头中未包含：x-wx-encrypted-data');
        }
        $sessionKey = $user['session_key'];
        app('log')->debug('x-wx-encrypted-data:' . var_export($encryptedData, true));
        app('log')->debug('x-wx-iv:' . var_export($iv, true));

        $data = WechatService::decryptData($sessionKey, $encryptedData, $iv);
        return makeResponse($data, 'success', 200);
    }

    public function getPhoneNumber(Request $request)
    {
        $encryptedData = $request->input('encrypted_data', '');
        $iv = $request->input('iv', '');
        $user = $request->user();
        if (!$user) {
            return makeResponse([], '请使用微信登陆', 401);
        }

        $sessionKey = $user['session_key'];
        $result = WechatService::decryptData($sessionKey, $encryptedData, $iv);
        $data = json_decode($result, true);
        if ($data) {
            $phoneNumber = $data['phoneNumber'];
            $user->phone = $phoneNumber;
            $user->save();
            return makeResponse(['phone' => $phoneNumber], 'success', 200);
        } else {
            return makeResponse([], 'error', 500);
        }
    }



}
